# -*- coding: utf-8 -*-
import base64
import json
import random
from collections import OrderedDict

import requests
from Crypto.Hash import SHA256
from Crypto.PublicKey import RSA
from Crypto.Signature import PKCS1_v1_5 as Signature_pkcs1_v1_5
from django.conf import settings

from async import async_job
from common.order import db as order_db
from common.order.model import PAY_STATUS
from common.utils import track_logging
from common.utils.exceptions import ParamError

_LOGGER = track_logging.getLogger(__name__)

APP_CONF = {
    'c100003': {  # witch 支付宝 2.1
        'API_KEY': '661b8f5919764f23bfe5374bd9222753',
        'gateway': 'http://101.132.178.177:8080/xiaorong/payment/payOrder',
        'query_gateway': 'http://101.132.178.177:8080/xiaorong/payment/queryOrder',
        'pub_key': """-----BEGIN PUBLIC KEY-----
MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAwofLhjF1+jg3OqDn3ZqDdNWpirF2QdlhHt+AeVirHIewfxUY6e2oZLW6V7VkZw+BZoy48a5FOMQnBTE6UPiJwLIIyRFih74ZX42+DHTKHUqgfiDrVuCSD+ayb58AkG28tCEAhd/XWy26HO0u4mZhblHJGJoGWppL3foq+N2AFP+qLFqlivQn7vU3JC4cB0MalfDFSPcFstgLlLlydy3UWBBMRANqiooDs+Zr2nAS/Sd+HBm3ZVI5o+yGFfgdeSnA9s2qPuhQSRGkqNFaSmTO5wXcNNEE8sqsXu81byEjyigerxOTIjBES18tZVnQITI4fWY4CwcCL++EoIVmMr+pzwIDAQAB
-----END PUBLIC KEY-----""",
        'pri_key': """-----BEGIN PRIVATE KEY-----
MIIEvwIBADANBgkqhkiG9w0BAQEFAASCBKkwggSlAgEAAoIBAQDCh8uGMXX6ODc6oOfdmoN01amKsXZB2WEe34B5WKsch7B/FRjp7ahktbpXtWRnD4FmjLjxrkU4xCcFMTpQ+InAsgjJEWKHvhlfjb4MdModSqB+IOtW4JIP5rJvnwCQbby0IQCF39dbLboc7S7iZmFuUckYmgZamkvd+ir43YAU/6osWqWK9Cfu9TckLhwHQxqV8MVI9wWy2AuUuXJ3LdRY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pyalXgVxVUMDbySuSkpKZsIvMMJmT3lKgkuQKDT25S+bHJ7uWYGC40wYiEsH3z9j7kYEcRUjaYTRzcsJqEzXKWQpVokgSHCagqtGPuj3swKBgQD3o6PaUQCdaGtaDCAmpq39jtddOq0ihbxCVhEHQNsjpyQPLqk6eAg0OgXuzoaPGhXq2PeO7ty3BUcJ++/XL+zrjYxCUbtpMVPW25GtKtkrxmmVV0UMmf6jm54PYILgAsR69kyw1hXojuOxCmNu3fcmz66Q3aU3iaojbcVkJvv1SA==
-----END PRIVATE KEY-----""",

    },
    'c100006': {  # witch 支付宝 2.2
        'API_KEY': '46597c37fe1b4e68961d893fd46040e0',
        'gateway': 'http://101.132.178.177:8080/xiaorong/payment/pay',
        'query_gateway': 'http://101.132.178.177:8080/xiaorong/payment/queryOrder',
        'pub_key': """-----BEGIN PUBLIC KEY-----
MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEA6H6ftD1LW4Y6OhWt3ykoAokMkoXbAJUHinC0n/YgJQJ4Stg8+GIjogC/NSrVrkeRwc6hucKMn6BsEkXKOh78/A3ueY0KOqzKGTM5w5jECJ0eEJqLDaflFrcyqrxrwv2W/OBDpilPHV3KxfWY/N1iNBq9DDo9P5xzA0DeuecKgAyF+NfTNlW2KGkNG9/tb9S86SCjTfxD7ZcKWIOzcAraPJQQ8du8kc+WOKZfrfCZs4Ca+naYxVCoBsBfO6F11e3xt/EoJjM99EuKNtzKRNu5HjAi/f/EK4tgL7JGdauGONT2LQvdl58SLcSpGpQtAXXWNu7C0FC8T45LeTbxqHUL9wIDAQAB
-----END PUBLIC KEY-----""",
        'pri_key': """-----BEGIN PRIVATE KEY-----
MIIEvgIBADANBgkqhkiG9w0BAQEFAASCBKgwggSkAgEAAoIBAQDofp+0PUtbhjo6Fa3fKSgCiQyShdsAlQeKcLSf9iAlAnhK2Dz4YiOiAL81KtWuR5HBzqG5woyfoGwSRco6Hvz8De55jQo6rMoZMznDmMQInR4QmosNp+UWt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ynkF9GWgwKBgQCuWsCXjozIJqkU1PVHW8UclSjCeahs0Rr6d7KOrYp/zpacFWJlCJI0YFTENG704il/ppqbl5a0c1qIHePGWPjeuLKgl20mexw72+MJkB/WxAOI3Vy065jhbuavJbg/pz7TRPd3ZFE6Z+4/167tH6oCz0vIcNTfMBFY6ivfrmyEQQKBgGK7dNNCRm92ugrJfQF0AODjYeuHltrKnquDgOrOe9pchqmLjoIV05kGy8xLklhUzv2xzN7x90rSh+cHOpOTZRUWz/Mmt8QPwQl/mei/HfKVda2oMricYpN1A/FLHQkeQFstmh2Ft0VsOjWcFbtSWlT68axliLbiPFW3SnPz8fuO
-----END PRIVATE KEY-----""",
    },
}


def _get_api_key(mch_id):
    return APP_CONF[mch_id]['API_KEY']


def _get_gateway(mch_id):
    return APP_CONF[mch_id]['gateway']


def _get_query_gateway(mch_id):
    return APP_CONF[mch_id]['query_gateway']


def _get_private_key(mch_id):
    return APP_CONF[mch_id]['pri_key']


def _gen_sign(message, app_id):
    key = RSA.importKey(_get_private_key(app_id))
    h = SHA256.new(message)
    signer = Signature_pkcs1_v1_5.new(key)
    signature = signer.sign(h)
    return base64.b64encode(signature)


def verify_notify_sign(params, key, app_id):
    sign = params['sign']
    params.pop('sign')
    calculated_sign = generate_sign(params, key, app_id)
    if sign != calculated_sign:
        _LOGGER.info("pinduobaopay sign: %s, calculated sign: %s", sign, calculated_sign)
        raise ParamError('sign not pass, data: %s' % params)


# success
def check_notify_sign(request, mer_id):
    key = _get_api_key(mer_id)
    data = dict(request.POST.iteritems())
    _LOGGER.info("pinduobaopay notify data: %s", data)
    verify_notify_sign(data, key, mer_id)
    pay_id = data['order_no']
    if not pay_id:
        _LOGGER.error("fatal error, out_trade_no not exists, data: %s" % data)
        raise ParamError('pinduobaopay event does not contain pay ID')

    pay = order_db.get_pay(int(pay_id))
    if not pay:
        raise ParamError('pay_id: %s invalid' % pay_id)
    if pay.status != PAY_STATUS.READY:
        raise ParamError('pay %s has been processed' % pay_id)

    mch_id = pay.mch_id
    trade_status = str(data['pay_status'])
    trade_no = data['o_id']
    total_fee = float(data['pay_amount']) / 100.0

    discount = float(json.loads(pay.extend or '{}').get('discount', 0))
    extend = {
        'discount': discount,
        'trade_status': trade_status,
        'trade_no': trade_no,
        'total_fee': total_fee
    }

    from common.channel.pay import check_channel_order
    check_channel_order(pay_id, total_fee, mer_id)
    if trade_status == '1':  # 0:未支付 1:支付成功
        _LOGGER.info('pinduobaopay check order success, mch_id:%s pay_id:%s' % (mch_id, pay_id))
        order_db.add_pay_success(mch_id, pay_id, total_fee, trade_no, extend)
        # async notify
        async_job.notify_mch(pay_id
                             )


def _gen_sign_str(parameter):
    s = ''
    for k in sorted(parameter.keys()):
        if parameter[k] is None or parameter[k] == '':
            continue
        s += '%s=%s&' % (k, parameter[k])
    return s[:len(s) - 1]


def generate_sign(parameter, key, app_id):
    s = _gen_sign_str(parameter)
    print s + key
    return _gen_sign(s + key, app_id)


def _fix_pay_amount(pay, pay_amount):
    extend = json.loads(pay.extend or '{}')
    if pay_amount >= 10 and int(pay_amount) == pay_amount:
        discount = random.randint(1, 10)
        pay_amount = pay_amount - float(discount) / 100
        extend.update({'discount': str(float(discount) / 100)})
        order_db.fill_extend(pay.id, extend)
    return pay_amount


# 2.2的接口出问题暂停了。要用c10003商户的
def create_ali_charge(pay, pay_amount, info):
    ''' 创建订单 '''
    mer_id = info['app_id']
    key = _get_api_key(mer_id)
    parameter_dict = OrderedDict((
        ("app_id", mer_id),
        ("order_no", str(pay.id)),
        ("pay_type", "2"),  # 1:微信 2:支付宝
        ("pay_amount", str(int(pay_amount * 100))),
        ("order_name", 'charge'),
        ("order_extra", 'charge'),
        ('notify_url', '{}/pay/api/{}/pinduobaopay/{}'.format(settings.NOTIFY_PREFIX, settings.NOTIFY_PATH, mer_id)),
        ("ip", _get_device_ip(info)),

    ))
    parameter_dict['sign'] = generate_sign(parameter_dict, key, mer_id)
    _LOGGER.info("pinduobaopay create  data: %s ", parameter_dict)
    headers = {'Content-Type': 'application/x-www-form-urlencoded'}
    response = requests.post(_get_gateway(mer_id), data=parameter_dict, headers=headers, timeout=3)
    _LOGGER.info("pinduobaopay create charge rsp data: %s %s", response.status_code, response.text)
    res_obj = json.loads(response.text)
    return res_obj['pay_info']


# 根据通道要求 修改金额，不优惠
def change_pay_amount(pay_amount):
    if pay_amount >= 10 and int(pay_amount) % 10 == 0:
        return pay_amount - 1
    else:
        return pay_amount


def create_charge(pay, pay_amount, info):
    service = info.get('service')
    pay_amount = change_pay_amount(pay_amount)
    if service == 'alipay':
        url = create_ali_charge(pay, pay_amount, info)  # v2.2
    else:
        url = create_ali1_charge(pay, pay_amount, info)  # 2.1
    return {'charge_info': url}


def _get_device_ip(info):
    try:
        extra = json.loads(info['extra'])
    except:
        extra = {}
    user_info = extra.get('user_info', {})
    return user_info.get('device_ip') or '127.0.0.1'


# 该接口由于上游原因，暂不使用
def create_ali1_charge(pay, pay_amount, info):
    ''' 创建订单 '''
    mer_id = info['app_id']
    key = _get_api_key(mer_id)
    parameter_dict = OrderedDict((
        ("app_id", mer_id),
        ("order_no", str(pay.id)),
        ("pay_type", "2"),  # 2:wap支付 3:pc支付
        ("pay_amount", str(int(pay_amount * 100))),
        ("order_name", 'charge'),
        ("order_extra", 'charge'),
        ('front_notify_url',
         '{}/pay/api/{}/pinduobaopay/{}/'.format(settings.NOTIFY_PREFIX, settings.RETURN_PATH, pay.id)),
        ('notify_url', '{}/pay/api/{}/pinduobaopay/{}'.format(settings.NOTIFY_PREFIX, settings.NOTIFY_PATH, mer_id)),
        ("ip", _get_device_ip(info)),

    ))
    sign = generate_sign(parameter_dict, key, mer_id)
    url = _get_gateway(mer_id) + '?' + _gen_sign_str(parameter_dict) + '&sign=' + sign
    _LOGGER.info("pinduobaopay create charge data: %s", url)
    return url


def _get_str(s, start, end):
    p1 = s.index(start)
    p2 = s.index(end, p1 + len(start))
    if p2 > p1:
        return s[p1 + len(start): p2]
    else:
        return ''


def query_charge(pay_order, app_id):
    ''' 查询订单 '''
    pay_id = pay_order.id
    api_key = _get_api_key(app_id)
    parameter_dict = OrderedDict((
        ("app_id", app_id),
        ("order_no", str(pay_order.id)),
    ))
    s = _gen_sign_str(parameter_dict)
    parameter_dict['sign'] = _gen_sign(s + api_key, app_id)
    _LOGGER.info('pinduobaopay query data %s: ', parameter_dict)
    headers = {'Content-Type': 'application/x-www-form-urlencoded'}
    response = requests.post(_get_query_gateway(app_id), data=parameter_dict, headers=headers, timeout=3)
    _LOGGER.info('pinduobaopay query response, status_code: %s, %s: ', response.status_code, response.text)
    if response.status_code == 200:
        data = json.loads(response.text)
        trade_status = str(data['pay_status'])
        trade_no = data['o_id']
        total_fee = float(data['pay_amount']) / 100.0

        discount = float(json.loads(pay_order.extend or '{}').get('discount', 0))
        extend = {
            'discount': discount,
            'trade_status': trade_status,
            'trade_no': trade_no,
            'total_fee': total_fee
        }

        # 0:未支付 1:支付成功
        if trade_status == '1':
            _LOGGER.info('pinduobaopay query order success, pay_id:%s' % pay_id)
            order_db.add_pay_success(pay_order.mch_id, pay_order.id,
                                     total_fee, trade_no, extend)
            async_job.notify_mch(pay_order.id)
    else:
        _LOGGER.warn('pinduobaopay data error, status_code: %s', response.status_code)
